package core

import (
	"io"
	"openzbox.com/driver/conn/serial"
)

type CANCallback func(port string, msg []byte)

type CANPort struct {
	Name string `json:"name"`
	Type string `json:"type"`
	//R120   bool               `json:"r120,omitempty"`
	Booton bool          `json:"booton"`
	Ioctrl string        `json:"ioctrl,omitempty"`
	Opts   serial.Config `json:"opts"`

	com io.ReadWriteCloser `json:"-"`
	ch  chan bool
}

func (can *CANPort) GetName() string {
	return can.Name
}
func (can *CANPort) GetType() string {
	return can.Type
}

func (can *CANPort) GetOpts() serial.Config {
	return can.Opts
}

func NewCANPort(name string, dtype string, opts serial.Config) (*CANPort, error) {
	var s = &CANPort{Name: name, Type: dtype, Opts: opts, ch: make(chan bool)}
	/*s.cmds = make(map[string](string))
	s.pwc = pca9554.NewPCA9554()
	s.pwc.SetAllOutput()*/
	return s, nil
}

func (can *CANPort) SetOpts(c serial.Config) {
	can.Opts = c
}

func (can *CANPort) OpenWithOpts(callback Callback, args ...interface{}) error {
	return nil
}

func (can *CANPort) Open(callback Callback) error {
	return nil
}

func (can *CANPort) SendString(data string) error {
	_, err := can.com.Write([]byte(data))
	return err
}

func (can *CANPort) SendBytes(data []byte) error {
	_, err := can.com.Write(data)
	return err
}

/*关闭*/
func (can *CANPort) Close() error {
	//fmt.Printf("port.com %v %v", port, port.com)
	close(can.ch)
	return can.com.Close()
}

//ch <-chan bool
func (can *CANPort) IsClosed() bool {
	select {
	case <-can.ch:
		return true
	default:
	}
	return false
}
